const my = require('classes/lib/util.js');
const consts = require('classes/consts.js');
const user = require('classes/application/user.js');
const gameClass = require('classes/application/game.js');
const wechat = require('classes/application/wechat.js');
const md5 = require('classes/lib/md5.js');
const application = require('classes/application/application.js');
const updateManager = wx.getUpdateManager();
App({
  onLaunch: function (options) {
    // 展示本地存储能力
    console.log("app:version: " + consts.APP_VERSION);
    console.log("app:options="+JSON.stringify(options));
    my.L("app_scene", options.scene);
    this.globalData.scene = options.scene;
    this.globalData.systemInfo = wx.getSystemInfoSync();   
    console.log(this.globalData.systemInfo);
  },
  onShow : function(){
    console.log("app:onShow:invoke");
    console.log("app:onshow:openid="+this.globalData.openid);
  },
  step0_wxLogin : function(){
    var that = this;
    wx.checkSession({
      success: function () {
        console.log("app:step0_wxLogin:check session success");
        that.globalData.openid = my.L("cache_globalData_openid");
        console.log("app:step0_wxLogin:cache openid=" + that.globalData.openid);
        that.globalData.unionid = my.L("cache_globalData_unionid");
        console.log("app:step0_wxLogin:cache unionid=" + that.globalData.unionid);
        that.globalData.session_key = my.L("wx_session_key");
        console.log("app:step0_wxLogin:cache session_key=" + that.globalData.session_key);
        if (that.globalData.openid && that.globalData.session_key){
          that.step2_getUserInfo();
          that.globalData.step = 1;
        }else{
          that.__wxLogin();
        }
      },
      fail: function () {
        console.log("app:step0_wxLogin:check session fail");
        that.__wxLogin();
      }
    });
  },
  __wxLogin : function(){
    var that = this;
    wx.login({
      success: res => {
        console.log("app:__wxLogin:res:" + JSON.stringify(res));
        if (res.code) {
          that.globalData.wxloginCode = res.code;
          console.log("app:__wxLogin:code=" + res.code);
          that.globalData.step = 1;
          that.step1_getOpenid();
        }
      }
    });
  },
  step1_getOpenid : function(){
    console.log("app:step1_getOpenid:invoke");
    var that = this;
    wechat.getOpenid({
      app: consts.APP_CODE,
      code: this.globalData.wxloginCode,
      callback: function (data) {
        that.globalData.step = 1;
        that.globalData.src_openid = data.openid;
        that.globalData.openid = data.openid;
        that.globalData.session_key = data.session_key;
        console.log("app:step1_getOpenid:session_key=" + that.globalData.session_key);
        my.L("wx_session_key",data.session_key);
        console.log("app:step1_getOpenid:src_openid=" + data.openid);
        that.step2_getUserInfo();
      },
      error: function (code, msg) {
        my.error(that, {
          code: code,
          msg: msg,
          track: "WX_LOGIN ERROR",
        });
      }
    });    
  },
  step2_getUserInfo: function () {
    var that = this;
    if (that.globalData.userInfo) {
      console.log("app:userInfo allready exists");
      that.globalData.step = 2;
      that.step2_5_updateOpenId();
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      console.log("app:userInfo not exists");
      wx.getUserInfo({
        withCredentials:true,
        success: res => {
          that.globalData.step = 2;
          console.log("app:step2_getUserInfo:wx.getUserInfo ok");
          //console.log("app:getUserInfo=" + JSON.stringify(res));
          var _userInfo = res.userInfo;
          if(res.encryptedData && consts.USE_UNIONID==true){
            _userInfo = wechat.bizDataCrypt(
              that.globalData.session_key, 
              res.encryptedData, 
              res.iv
            );    
            if(!_userInfo){
              console.log("encrypte userInfo failed");
              _userInfo = res.userInfo;
            }else{
              that.globalData.unionid = _userInfo.unionId;
              my.L("cache_globalData_unionid", that.globalData.unionid);
              console.log("app:step2_getUserInfo:getUserInfo:unionId=" + _userInfo.unionId);
              that.globalData.openid = _userInfo.unionId;
              my.L("cache_globalData_openid", that.globalData.openid);
              console.log("app:step2_getUserInfo:getUserInfo:openid=" + that.globalData.openid);
            }                
          }
          that.globalData.userInfo = _userInfo;
          console.log("app:step2_getUserInfo:getUserInfo=" + JSON.stringify(_userInfo));
          my.L("cache_globalData_userInfo", _userInfo);
          that.step2_5_updateOpenId();
        },
        fail: function (res) {
          console.log("app:step2_getUserInfo:getUserInfo fail,navigate to wxauth");
          wx.navigateTo({
            url: '/pages/wxauth/wxauth',
          });
        }
      });
    }
  },
  step2_5_updateOpenId : function(){
    if (this.globalData.src_openid && this.globalData.unionid && consts.USE_UNIONID == true){
      var that = this;
      user.updateOpenid({
        openid: this.globalData.src_openid,
        unionid: this.globalData.unionid,
        callback: function (data) {
          console.log("app:step2_5_updateOpenId:" + JSON.stringify(data));
          that.globalData.step = 2.5;
          that.step3_getLocation();
        },
      });
    }else{
      console.log("app:step2_5_updateOpenId:src_openid or uniond lost or USE_UNIONID is false");
      this.globalData.step = 2.5;
      this.step3_getLocation();
    }
  },
  step3_getLocation: function () {
    var that = this;
    wx.getLocation({
      type: "wgs84",
      success: function (res) {
        that.globalData.step = 3;
        console.log("app:step3_getLocation:success");
        that.globalData.latitude = res.latitude;
        that.globalData.longitude = res.longitude;
        that.step4_sanduLogin();
        var speed = res.speed;
        var accuracy = res.accuracy;
      },
      fail: function () {
        console.log("app:step3_getLocation:fail");
        that.globalData.latitude = 0;
        that.globalData.longitude = 0;
        that.globalData.step = 3;
        that.step4_sanduLogin(0, 0);
      },
    });
  },
  step4_sanduLogin: function (redirectUrl) {
    if(!this.globalData.openid){
      this.step0_wxLogin();
    }else{
      console.log("app:step4_sanduLogin:invoke");
      console.log("app:step4_sanduLogin:openid="+this.globalData.openid);
      var that = this;
      var uid = my.ival(my.L("user_data_uid"));
      if(uid>0){
        this.globalData.uid = uid;
      }
      var params = {};
      params.oid = this.globalData.openid;
      params.rid = this.globalData.from_user_id;
      params.unionid = this.globalData.unionid;
      params.scene = this.globalData.scene;    
      params.uid = uid;
      params.head_pic = this.globalData.userInfo.avatarUrl;
      params.nick_name = this.globalData.userInfo.nickName;
      params.sex  = 0,
      params.lng = this.globalData.latitude;
      params.lat = this.globalData.longitude;
      params.province = this.globalData.userInfo.province;
      params.city = this.globalData.userInfo.city;
      params.country = this.globalData.userInfo.country;
      this.globalData.loginParams = params;
      console.log("app:step4_sanduLogin:params:uid=" + params.uid);
      application.init({
        params: params, 
        callback : function (data) {
          //console.log("app:step4_sanduLogin:application init="+JSON.stringify(data));
          that.globalData.sanduUserInfo = data.user;
          my.L("user_data_uid",data.user.game.uid);
          that.globalData.cfg = {};
          that.globalData.cfg.games = data.games;
          that.updateGame(data.user.game);

          that.globalData.cfg.game.reward_boundary = my.ival(that.globalData.cfg.game.reward_boundary);
          that.globalData.cfg.game.game_level = data.user.game.level;
          console.log("app:step4_sanduLogin:cfg:game=" + JSON.stringify(that.globalData.cfg.game));

          that.globalData.cfg.app = data.setting;
          console.log("app:step4_sanduLogin:cfg:app=" + JSON.stringify(that.globalData.cfg.app));
          that.globalData.address = (data.address.length && data.address.length > 0) ? data.address[0] : null;

          console.warn("============= app:init ======================");
          console.warn("==== user_id=" + data.user.uid);
          console.warn("==== username=" + data.user.username);
          console.warn("==== mobile=" + data.user.mobile);
          console.warn("==== balance=" + data.user.balance);
          console.warn("==== address=" + JSON.stringify(that.globalData.address));
          console.warn("==== game=" + JSON.stringify(that.globalData.game));
          console.warn("==== cfg.game=" + JSON.stringify(that.globalData.cfg.game));
          console.warn("==== cfg.app=" + JSON.stringify(that.globalData.cfg.app));
          console.warn("---------------------------------------------");

          that.bindSanduUserInfo();
          that.globalData.step = 4;
          console.log("app:step4_sanduLogin:step=4");
          if (redirectUrl){
            console.log("app:step4_sanduLogin:redirectTo=" + redirectTo);
            wx.redirectTo({
              url: redirectUrl,
            });
          }
        },
        error : function(code,msg){
          console.log("app:step4_sanduLogin:application fail");
          my.alert('['+code+']'+msg);
        }
      });
    }
  },
  getLocation: function (callback) {
    if(this.globalData.latitude>0){
      if (typeof (callback) == "function") {
        callback(this.globalData.latitude,this.globalData.longtitude);
      }
    }else{
      var that = this;
      wx.getLocation({
        type: "wgs84",
        success: function (res) {
          that.globalData.latitude = res.latitude;
          that.globalData.longitude = res.longitude;
          if (typeof (callback) == "function") {
            callback(res.latitude, res.longitude);
          }
        },
        fail: function () {
          if (typeof (callback) == "function") {
            callback(0, 0);
          }
        },
      });
    }
  },  
  getUserInfo : function(callback){
    if(this.globalData.userInfo){
      if (typeof (callback) == "function") {
        callback(this.globalData.userInfo);
      }
    }else{
      wx.getUserInfo({
        success: res => {
          this.globalData.userInfo = res.userInfo;
          this.bindSanduUserInfo();
          if(typeof(callback)=="function"){
            callback(res.userInfo);
          }
        }
      });
    }
  },
  bindSanduUserInfo : function(){
    if (!this.globalData.sanduUserInfo 
      || !this.globalData.userInfo){
      console.log("app:bindSanduUserInfo:bind sandu user failed");
        return;
      }
    var user = this.globalData.sanduUserInfo;
    var gu = this.globalData.userInfo;
    gu.headPic = gu.avatarUrl;
    gu.user_id = my.ival(user.uid);
    gu.user_name = my.val(user.username);
    gu.username = gu.user_name;
    gu.nickname = user.nickname;
    gu.mobile = my.val(user.mobile);
    if(!gu.mobile || gu.mobile==''){
      gu.mobile = my.L("get_phone_number");
    }
    gu.gender = my.val(user.gender);
    gu.balance = my.ival(user.balance);
    gu.affiliate_id = my.ival(user.affiliate_id);
    if (gu.guest == 1
      && user.user_name) {
      gu.nickName = "U" + user.user_name;
    }
    gu.role = user.game.role;
    if (user.store && user.store.store_id>0) {
      gu.store = user.store;
    } else {
      gu.store = this.getEmptyStoreInfo();
    }  
    if (gu.store.tel=="undefined"){
      gu.store.tel = null;
    }  
    this.globalData.userInfo = gu;
    console.log("app:bind sandu user_id="+this.globalData.userInfo.user_id);
  },
  getEmptyStoreInfo : function(){
    return {
      store_id: 0,
      store_name: '',
      lng: 0,
      lat: 0,
      address: '',
      tel: '',
      store_code: '',
      province: '',
      city: '',
      distinct: '',
      is_reservble: ''
    };    
  },
  getEmptyWxUserInfo : function(){
    return {
      nickName: "Guest",
      gender: 0,
      province: "中国",
      city: "",
      avaterUrl: "/res/icon/avater.png",
      guest: 0,
    };
  },
  clearLoginTimer : function(){
    if (this.globalData.loginTimer){
      console.log("app:clearLoginTimer");
      clearInterval(this.globalData.loginTimer);
      this.globalData.loginTimer = null;
    }else{
      console.log("app:clearLoginTimer:timer is null");
    }
  },
  startLoginTimer : function(func){
    console.log("app:startLoginTimer");
    this.globalData.loginTimer = setInterval(func, 50);
  },
  statics : function(){
    return "http://mp-mysj.sanduapp.com/static/wxapp";
  },
  setGender : function(gender){
    this.globalData.game.gender = gender;
    this.globalData.themes = (gender==1)?"male":"female";
    var levelIndex = this.globalData.game.level - 1;
    if (levelIndex < 0) {
      levelIndex = 0;
    }    
    this.globalData.cfg.game = this.globalData.cfg.games[gender][levelIndex];
    console.log("app:setGender:themes=" + this.globalData.themes);
  },
  updateGame : function(game){
    if(game && game.uid>0){
      var levelIndex = game.level - 1;
      if (levelIndex < 0) {
        levelIndex = 0;
      }    
      this.globalData.cfg.game = this.globalData.cfg.games[game.gender][levelIndex];
      console.log("app:updateGame:check game flow_order,order="+game.order);
      console.log("app:updateGame:check game flow_order,level=" + game.level);
      if (game.order < 1 && this.orderExist(game.uid,game.level)){
        console.log("app:updateGame:check flow order:has order,set order and trask");
        game.order = 1;
        game.task = 1;
      }
      this.globalData.game = gameClass.parse(game);
      this.setGender(game.gender);
    }
  },
  orderPush : function(){
    var list = my.L("flow_order_list");
    if (!list){
      list = [];
    }
    list.push(this.globalData.game);
    console.log("app:orderPush:push game=" + JSON.stringify(this.globalData.game));
    this.globalData.flow_order_list = list;
    my.L("flow_order_list", list);
  },
  orderExist : function(uid,level){
    var list = my.L("flow_order_list");
    if (!list && list.length>0) {
      for(var i=0;i<list.length;i++){
        if(list[i].uid==uid && list[i].level==level){
          return true;
        }
      }
    }
    return false;
  },
  share : function(){
    console.log("app:share:uid="+this.globalData.game.uid);
    return {
      title: consts.APP_SHARE_TITLE,
      path: "pages/index/index?rid=" + this.globalData.game.uid,
      imageUrl: "../../res/images/share.png",
      success: function (res) {
        wx.navigateBack({
          delta: -1
        });
      },
      fail: function (res) { }
    }    
  },
  globalData: {
    src_openid : null,
    step : 0,//启动加载进度
    systemInfo : null,
    wxloginCode : null,
    openid : '',
    unionid : '',
    activity_id :0,
    userInfo: null,
    sanduUserInfo:null,
    session_key:'',
    scene:0,
    latitude : 0,
    longitude : 0,
    from_user_id:0,
    themes : "",
    loginTimer : null,
    game : null,
    index_options:null,
    flow_order_list : [],
  },
})